/**
 * 举报路由模块
 * @author HalRui
 * @version 1.0.0
 * @description 定义举报相关的API接口，包括举报创建、查询、状态管理、处理流程、统计分析等功能
 * @date 2025年9月27日
 */

const express = require('express');
const router = express.Router();
const reportsApi = require('../../api/reports-api');

/**
 * 创建举报
 * POST /reports/create
 */
router.post('/create', async (req, res) => {
    try {
        const {
            reporterId,
            targetType,
            targetId,
            reportType,
            reason,
            description,
            evidence,
            reporterIp
        } = req.body;
        
        // 参数验证
        if (!reporterId || isNaN(parseInt(reporterId))) {
            return res.status(400).json({
                success: false,
                message: '举报者ID无效'
            });
        }
        
        if (!targetType || !['video', 'comment', 'user', 'message'].includes(targetType)) {
            return res.status(400).json({
                success: false,
                message: '被举报对象类型无效'
            });
        }
        
        if (!targetId || isNaN(parseInt(targetId))) {
            return res.status(400).json({
                success: false,
                message: '被举报对象ID无效'
            });
        }
        
        const validReportTypes = [
            'spam', 'harassment', 'hate_speech', 'violence', 'adult_content',
            'copyright', 'misinformation', 'privacy', 'fraud', 'other'
        ];
        if (!reportType || !validReportTypes.includes(reportType)) {
            return res.status(400).json({
                success: false,
                message: '举报类型无效'
            });
        }
        
        if (!reason || reason.trim().length === 0) {
            return res.status(400).json({
                success: false,
                message: '举报原因不能为空'
            });
        }
        
        if (reason.trim().length > 500) {
            return res.status(400).json({
                success: false,
                message: '举报原因不能超过500个字符'
            });
        }
        
        if (description && description.length > 2000) {
            return res.status(400).json({
                success: false,
                message: '详细描述不能超过2000个字符'
            });
        }
        
        // 验证证据附件
        if (evidence && Array.isArray(evidence)) {
            if (evidence.length > 10) {
                return res.status(400).json({
                    success: false,
                    message: '证据附件不能超过10个'
                });
            }
            
            for (const item of evidence) {
                if (!item.type || !['image', 'video', 'audio', 'document'].includes(item.type)) {
                    return res.status(400).json({
                        success: false,
                        message: '证据附件类型无效'
                    });
                }
                
                if (!item.url || item.url.trim().length === 0) {
                    return res.status(400).json({
                        success: false,
                        message: '证据附件URL不能为空'
                    });
                }
            }
        }
        
        const reportData = {
            reporterId: parseInt(reporterId),
            targetType,
            targetId: parseInt(targetId),
            reportType,
            reason: reason.trim(),
            description: description || '',
            evidence: evidence || [],
            reporterIp: reporterIp || req.ip
        };
        
        const result = await reportsApi.createReport(reportData);
        
        if (result.success) {
            res.status(201).json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('创建举报接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取举报列表
 * GET /reports/list
 */
router.get('/list', async (req, res) => {
    try {
        const {
            status,
            reportType,
            targetType,
            priority,
            handlerId,
            reporterId,
            keyword,
            startDate,
            endDate,
            page = 1,
            limit = 20,
            sortBy = 'createAt',
            sortOrder = 'desc'
        } = req.query;
        
        const pageNum = parseInt(page);
        const limitNum = parseInt(limit);
        
        // 参数验证
        if (pageNum < 1 || limitNum < 1 || limitNum > 100) {
            return res.status(400).json({
                success: false,
                message: '无效的分页参数'
            });
        }
        
        // 验证排序字段
        const validSortFields = ['createAt', 'updateAt', 'priority', 'status'];
        if (!validSortFields.includes(sortBy)) {
            return res.status(400).json({
                success: false,
                message: '无效的排序字段'
            });
        }
        
        const options = {
            page: pageNum,
            limit: limitNum,
            sortBy,
            sortOrder
        };
        
        if (status) options.status = status;
        if (reportType) options.reportType = reportType;
        if (targetType) options.targetType = targetType;
        if (priority) options.priority = priority;
        if (handlerId) options.handlerId = parseInt(handlerId);
        if (reporterId) options.reporterId = parseInt(reporterId);
        if (keyword) options.keyword = keyword.trim();
        if (startDate) options.startDate = startDate;
        if (endDate) options.endDate = endDate;
        
        const result = await reportsApi.getReportList(options);
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('获取举报列表接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取举报详情
 * GET /reports/detail/:reportId
 */
router.get('/detail/:reportId', async (req, res) => {
    try {
        const { reportId } = req.params;
        
        // 参数验证
        if (!reportId || isNaN(parseInt(reportId))) {
            return res.status(400).json({
                success: false,
                message: '无效的举报ID'
            });
        }
        
        const result = await reportsApi.getReportDetail(parseInt(reportId));
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(404).json(result);
        }
    } catch (error) {
        console.error('获取举报详情接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 更新举报状态
 * PUT /reports/status/:reportId
 */
router.put('/status/:reportId', async (req, res) => {
    try {
        const { reportId } = req.params;
        const { status, handlerId } = req.body;
        
        // 参数验证
        if (!reportId || isNaN(parseInt(reportId))) {
            return res.status(400).json({
                success: false,
                message: '无效的举报ID'
            });
        }
        
        const validStatuses = ['pending', 'reviewing', 'resolved', 'rejected', 'closed'];
        if (!status || !validStatuses.includes(status)) {
            return res.status(400).json({
                success: false,
                message: '无效的状态'
            });
        }
        
        if (handlerId && isNaN(parseInt(handlerId))) {
            return res.status(400).json({
                success: false,
                message: '无效的处理人员ID'
            });
        }
        
        const result = await reportsApi.updateReportStatus(
            parseInt(reportId),
            status,
            handlerId ? parseInt(handlerId) : null
        );
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('更新举报状态接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 处理举报
 * PUT /reports/resolve/:reportId
 */
router.put('/resolve/:reportId', async (req, res) => {
    try {
        const { reportId } = req.params;
        const { action, reason, details, handlerId } = req.body;
        
        // 参数验证
        if (!reportId || isNaN(parseInt(reportId))) {
            return res.status(400).json({
                success: false,
                message: '无效的举报ID'
            });
        }
        
        const validActions = ['no_action', 'warning', 'content_removal', 'account_suspension', 'account_ban', 'other'];
        if (!action || !validActions.includes(action)) {
            return res.status(400).json({
                success: false,
                message: '无效的处理动作'
            });
        }
        
        if (!handlerId || isNaN(parseInt(handlerId))) {
            return res.status(400).json({
                success: false,
                message: '缺少处理人员ID'
            });
        }
        
        const resolutionData = {
            action,
            reason: reason || '',
            details: details || ''
        };
        
        const result = await reportsApi.resolveReport(
            parseInt(reportId),
            resolutionData,
            parseInt(handlerId)
        );
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('处理举报接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 添加管理员备注
 * POST /reports/note/:reportId
 */
router.post('/note/:reportId', async (req, res) => {
    try {
        const { reportId } = req.params;
        const { adminId, note } = req.body;
        
        // 参数验证
        if (!reportId || isNaN(parseInt(reportId))) {
            return res.status(400).json({
                success: false,
                message: '无效的举报ID'
            });
        }
        
        if (!adminId || isNaN(parseInt(adminId))) {
            return res.status(400).json({
                success: false,
                message: '缺少管理员ID'
            });
        }
        
        if (!note || note.trim().length === 0) {
            return res.status(400).json({
                success: false,
                message: '备注内容不能为空'
            });
        }
        
        if (note.trim().length > 1000) {
            return res.status(400).json({
                success: false,
                message: '备注内容不能超过1000个字符'
            });
        }
        
        const result = await reportsApi.addAdminNote(
            parseInt(reportId),
            parseInt(adminId),
            note.trim()
        );
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('添加管理员备注接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 删除举报
 * DELETE /reports/delete/:reportId
 */
router.delete('/delete/:reportId', async (req, res) => {
    try {
        const { reportId } = req.params;
        
        // 参数验证
        if (!reportId || isNaN(parseInt(reportId))) {
            return res.status(400).json({
                success: false,
                message: '无效的举报ID'
            });
        }
        
        const result = await reportsApi.deleteReport(parseInt(reportId));
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('删除举报接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取举报统计信息
 * GET /reports/stats
 */
router.get('/stats', async (req, res) => {
    try {
        const { startDate, endDate, groupBy } = req.query;
        
        const options = {};
        if (startDate) options.startDate = startDate;
        if (endDate) options.endDate = endDate;
        if (groupBy) options.groupBy = groupBy;
        
        const result = await reportsApi.getReportStats(options);
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('获取举报统计接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取用户举报历史
 * GET /reports/user/:reporterId
 */
router.get('/user/:reporterId', async (req, res) => {
    try {
        const { reporterId } = req.params;
        const { page = 1, limit = 20, status } = req.query;
        
        // 参数验证
        if (!reporterId || isNaN(parseInt(reporterId))) {
            return res.status(400).json({
                success: false,
                message: '无效的用户ID'
            });
        }
        
        const pageNum = parseInt(page);
        const limitNum = parseInt(limit);
        
        if (pageNum < 1 || limitNum < 1 || limitNum > 100) {
            return res.status(400).json({
                success: false,
                message: '无效的分页参数'
            });
        }
        
        const options = {
            page: pageNum,
            limit: limitNum
        };
        
        if (status) options.status = status;
        
        const result = await reportsApi.getUserReportHistory(parseInt(reporterId), options);
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('获取用户举报历史接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 批量更新举报状态
 * PUT /reports/batch-status
 */
router.put('/batch-status', async (req, res) => {
    try {
        const { reportIds, status, handlerId } = req.body;
        
        // 参数验证
        if (!reportIds || !Array.isArray(reportIds) || reportIds.length === 0) {
            return res.status(400).json({
                success: false,
                message: '举报ID列表不能为空'
            });
        }
        
        if (reportIds.length > 100) {
            return res.status(400).json({
                success: false,
                message: '一次最多处理100个举报'
            });
        }
        
        // 验证所有ID都是数字
        const validReportIds = reportIds.filter(id => !isNaN(parseInt(id))).map(id => parseInt(id));
        if (validReportIds.length === 0) {
            return res.status(400).json({
                success: false,
                message: '没有有效的举报ID'
            });
        }
        
        const validStatuses = ['pending', 'reviewing', 'resolved', 'rejected', 'closed'];
        if (!status || !validStatuses.includes(status)) {
            return res.status(400).json({
                success: false,
                message: '无效的状态'
            });
        }
        
        if (handlerId && isNaN(parseInt(handlerId))) {
            return res.status(400).json({
                success: false,
                message: '无效的处理人员ID'
            });
        }
        
        const result = await reportsApi.batchUpdateReportStatus(
            validReportIds,
            status,
            handlerId ? parseInt(handlerId) : null
        );
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('批量更新举报状态接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 分配处理人员
 * PUT /reports/assign/:reportId
 */
router.put('/assign/:reportId', async (req, res) => {
    try {
        const { reportId } = req.params;
        const { handlerId } = req.body;
        
        // 参数验证
        if (!reportId || isNaN(parseInt(reportId))) {
            return res.status(400).json({
                success: false,
                message: '无效的举报ID'
            });
        }
        
        if (!handlerId || isNaN(parseInt(handlerId))) {
            return res.status(400).json({
                success: false,
                message: '缺少处理人员ID'
            });
        }
        
        const result = await reportsApi.assignHandler(
            parseInt(reportId),
            parseInt(handlerId)
        );
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('分配处理人员接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 更新举报优先级
 * PUT /reports/priority/:reportId
 */
router.put('/priority/:reportId', async (req, res) => {
    try {
        const { reportId } = req.params;
        const { priority } = req.body;
        
        // 参数验证
        if (!reportId || isNaN(parseInt(reportId))) {
            return res.status(400).json({
                success: false,
                message: '无效的举报ID'
            });
        }
        
        const validPriorities = ['low', 'medium', 'high', 'urgent'];
        if (!priority || !validPriorities.includes(priority)) {
            return res.status(400).json({
                success: false,
                message: '无效的优先级'
            });
        }
        
        const result = await reportsApi.updateReportPriority(
            parseInt(reportId),
            priority
        );
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('更新举报优先级接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

/**
 * 获取举报类型列表
 * GET /reports/types
 */
router.get('/types', async (req, res) => {
    try {
        const result = await reportsApi.getReportTypes();
        
        if (result.success) {
            res.json(result);
        } else {
            res.status(400).json(result);
        }
    } catch (error) {
        console.error('获取举报类型列表接口错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器内部错误'
        });
    }
});

module.exports = router;